package com.jtw.common.util;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

public class MobileCity {

    /**
     * 获取手机号码归属-省
     * @param mobileNumber 手机号码
     * @return
     */
	public static String getProvince(String mobileNumber) {
		String result = "";
		String urlString = "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=" + mobileNumber;
		try {
			URL url = new URL(urlString);
			InputStream in = url.openStream();
			// 解决乱码问题
			BufferedReader buffer = new BufferedReader(new InputStreamReader(in, "gb2312"));
			String line = null;
			StringBuffer sb = new StringBuffer();
			while ((line = buffer.readLine()) != null) {
				sb.append(line);
			}
			in.close();
			buffer.close();
			String jsonString = sb.toString();
			// 替换掉“__GetZoneResult_ = ”，让它能转换为JSON对象
			jsonString = jsonString.replaceAll("^[__]\\w{14}+[_ = ]+", "");
//			result = new Gson().fromJson(jsonString, JsonObject.class).get("province").getAsString();
//			System.out.println(jsonString);
			result = JSONObject.parseObject(jsonString).getString("province");
		} catch (Exception e) {
			e.printStackTrace();
			return result;
		}
		return result;
	}
	
	/**
	 * 手机归属地 - 通过聚合数据获取
	 * @param mobile
	 * @return {"resultcode":"200","reason":"Return Successd!","result":{"province":"广东","city":"深圳","areacode":"0755","zip":"518000","company":"中国移动","card":"移动神州行卡"},"error_code":0}
	 */
	public static String ownership(String mobile) {
		String result = "";
	    String urlString = "http://apis.juhe.cn/mobile/get?phone="+mobile+"&key=f0225799675872db9d6c533bc4ba5f18";
	    try {
			URL url = new URL(urlString);
			InputStream in = url.openStream();
			// 解决乱码问题
			BufferedReader buffer = new BufferedReader(new InputStreamReader(in, "utf-8"));
			String line = null;
			StringBuffer sb = new StringBuffer();
			while ((line = buffer.readLine()) != null) {
				sb.append(line);
			}
			in.close();
			buffer.close();
			String jsonString = sb.toString();
			System.out.println(jsonString);
//			JsonObject jsonObject = new Gson().fromJson(jsonString, JsonObject.class);
//			result = jsonObject.get("result").getAsJsonObject().get("province").getAsString()
//					+ jsonObject.get("result").getAsJsonObject().get("city").getAsString();
			JSONObject jsonObject = JSONObject.parseObject(jsonString);
			result = jsonObject.getJSONObject("result").getString("province")+jsonObject.getJSONObject("result").getString("city");
		} catch (Exception e) {
	    	e.printStackTrace();
			return result;
		}
	    return result;
	}

    public static void main(String[] args) {
        String mobile = "13530772012";
        System.out.println(getProvince(mobile));
        System.out.println(ownership(mobile));
    }
}
